import { HttpException, Injectable } from '@nestjs/common'
import { Student } from './student.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'

@Injectable()
export class StudentService {

	constructor(@InjectRepository(Student)
	private readonly studentRepository: Repository<Student>) { }

	root(): string {
		return 'studentService'
	}

	// 当student带有id时，save = update；当student没有id时，save = add
	async save(student: Student): Promise<any> {
		let res = await this.studentRepository.save(student)
		console.log("save: ", res)

		return res
	}

	async getAll(): Promise<any> {
		let res = await this.studentRepository.find()
		console.log("all student: ", res)

		return res
	}

	async get(option: object): Promise<any> {
		let res = await this.studentRepository.findBy(option)
		// let res = await this.studentRepository.find({name: 'longmao'})
		console.log("option student: ", res)

		return res
	}
	
	async updateById(post): Promise<any> {
	  const existPost = await this.studentRepository.findOne({where: { id: post.id }});
	  if (!existPost) {
	    throw new HttpException(`id为${post.id}的文章不存在`, 401);
	  }
	  const updatePost = this.studentRepository.merge(existPost, post);
	  return this.studentRepository.save(updatePost);
	}

	async remove(option: object): Promise<any> {
		let student = await this.studentRepository.findBy(option)
		if (student.length < 1) {
		  throw new HttpException(`文章不存在`, 401);
		}
		let res = await this.studentRepository.remove(student)
		console.log("remove: ", res)
		return res
	}
}
